﻿using AspectCore.DynamicProxy;
using Microsoft.Extensions.DependencyInjection;
using Service.Core.EfCoreRepository.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service.Core.EfCoreRepository.Attribute
{
    [AttributeUsage(AttributeTargets.Method, Inherited = true)]
    public class UnitOfWorkAttribute : AbstractInterceptorAttribute
    {
        public override int Order => 1;

        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            var _unitOfWork = context.ServiceProvider.GetRequiredService<ITransactionUnitOfWork>();
            if (_unitOfWork.CurrentTransaction == null)
            {
                try
                {
                    _unitOfWork.BeginTransaction();
                    await next(context);
                    await _unitOfWork.CommitAsync();
                }
                catch
                {
                    await _unitOfWork.RollbackAsync();
                    throw;
                }
            }
            else
            {
                // 如果事务已经开启，直接执行下一个逻辑
                await next(context);
            }
        }
    }
}
